import axios from "axios";
// import Qs from 'qs'
// import { Loading, MessageBox, Message } from 'element-ui'
import router from "../router";
import base from "@/utils/index";
import globalConfig from "@/config";
import { Toast } from "vant";

const baseFunc = base();
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 35000 // request timeout
});

// 拦截器loading白名单
const whiteList = [
  // '/city/face-recognition-page' // 人脸识别翻页
];

// 不需要token的列表
const noToken = [
  "/userInfo/mobileLogin" // 登录
];

// 那么 showFullScreenLoading() tryHideFullScreenLoading() 要干的事儿就是将同一时刻的请求合并。
// 声明一个变量 needLoadingRequestCount，每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。
// 调用tryHideFullScreenLoading()方法，needLoadingRequestCount - 1。needLoadingRequestCount为 0 时，结束 loading。
let needLoadingRequestCount = 0;
// let fullLoading
// 登录报错次数
// let loginErrorCount = 0
export const showLoading = () => {
  if (needLoadingRequestCount === 0) {
    // fullLoading = Loading.service({
    //   background: 'rgba(0, 0, 0, .2)',
    //   text: '加载中',
    //   spinner: 'el-icon-loading'
    // })
  }
  needLoadingRequestCount++;
};

export const tryHideLoading = () => {
  if (needLoadingRequestCount <= 0) return;
  needLoadingRequestCount--;
  if (needLoadingRequestCount === 0) {
    // fullLoading.close()
  }
};

service.interceptors.request.use(
  config => {
    if (config.url.startsWith('/classroom')) {
      config.baseURL = '' // 关键：绕过 baseURL
    }

    // 如果没有权限则先进行拦截
    let permission = baseFunc.getLocalStorage("apiPermission");
    let apiList = permission ? JSON.parse(permission) : [];
    let url = String(config.url).replace(String(config.baseURL), "");
    // config.headers.token = "c3716342-26c4-4484-8694-36058ad4f85c";
    if (apiList.indexOf(url) < 0 && globalConfig.needApiPermission) {
      // Message({
      //   message: '接口没有权限',
      //   type: 'error'
      // })
      return Promise.reject(new Error(config.url + " has no permission"));
    }
    if (config.url.startsWith('/classroom')) {
      config.url = config.url.replace('/gateway/api', '')
    }
    if (noToken.indexOf(config.url) < 0) {
      // console.log(noToken)
      if (sessionStorage.getItem("token")) {
        // 判断是否存在token，如果存在的话，则每个http header都加上token
        // config.headers.Authorization = sessionStorage.getItem("token");
        config.headers.token = sessionStorage.getItem("token");
      } else {
        router.push({ path: "/entering" });
      }
    }
    if (whiteList.indexOf(config.url) < 0) {
      showLoading();
    }

    return config;
  },
  err => {
    return Promise.reject(err);
  }
);

// http request 拦截器
service.interceptors.response.use(
  response => {
    // if (response.data.code === 1000) {
    //   if (loginErrorCount > 0) {
    //     loginErrorCount = 0
    //   } else {
    //     loginErrorCount++
    //     // Message({
    //     //   message: '登录信息失效，请重新登录',
    //     //   type: 'error'
    //     // })
    //     fullLoading.close()
    //     sessionStorage.setItem('token', '')
    //     router.push({ path: '/login' })
    //   }
    //   return Promise.reject(response)
    // } else if (response.data.code === 500) {
    //   // MessageBox.alert(response.data.msg, '', {}).then(function () {})
    // }
    tryHideLoading();
    if (response.status === 401) {
      Toast.fail("登录信息失效，请重新登录");
      sessionStorage.removeItem("token");
      router.push({ path: "/entering" });
      return Promise.reject(response);
    }
    return response.data;
  },
  error => {
    Toast.fail("信息失效，请重新登录");
    sessionStorage.removeItem("token");
    router.push({ path: "/error" });
  }
);

// 将axios 的 post 方法
export function $post(params) {
  return new Promise((resolve, reject) => {
    service
      .post(params.url, params.data)
      .then(res => {
        resolve(res);
      })
      .catch(err => {
        reject(err);
      });
  });
}

// 将axios 的 get 方法
export function $get(params) {
  return new Promise((resolve, reject) => {
    service
      .get(params.url, {
        params: params.data
      })
      .then(res => {
        resolve(res); // 返回请求成功的数据 data
      })
      .catch(err => {
        reject(err);
      });
  });
}

export default service;
